#include "rtc.h"
#include <io.h>
#include <interrupt/irq.h>
#include <klibc/stdio.h>
#include <klibc/typeconv.h>
#include <system/mod.h>


void rtc_print_time()
{
	printf("%d:%d:%d %d:%d:%d", rtc_data.hours, rtc_data.minutes, rtc_data.seconds, rtc_data.day, rtc_data.month, rtc_data.year);
}


/*
 * Imposta l'ora del kernel, aggiornata dal pit, cazzu cazzu
 */
static void rtc_callback(regs_t *r)
{
	rtc_data.hours = rtc_get_hours();
	rtc_data.minutes = rtc_get_minutes();
	rtc_data.seconds = rtc_get_seconds();
	rtc_data.month = rtc_get_month();
	rtc_data.year = rtc_get_year();
	rtc_data.day = rtc_get_day();
}


/*
 * Inizializza l'rtc
 */
uint32_t rtc_init()
{
	char prev;
	
	io_outb(0x70, 0x0B); //set the index to register B
	prev = io_inb(0x71); //read the current value of register B
	io_outb(0x70, 0x0B); //set the index again(a read will reset the index to register D)
	io_outb(0x71, prev | 0x40); //write the previous value or'd with 0x40. This turns on bit 6 of register D


	//char rate = 2; //rate must be above 2 and not over 15. (this is a safe-guard to be sure it isn't over 15)
	
	//io_outb(0x70, 0x0A); //set index to register A
	//prev = io_inb(0x71); //get initial value of register A
	//io_outb(0x70, 0x0A); //reset index to A
	//io_outb(0x71, (prev & 0xF0) | rate); //write only our rate to A. Note, rate is the bottom 4 bits.

	irq_install_handler(IRQ_RTC, &rtc_callback);
}



/*
 * Restituisce il in data la struttura contenente la data
 * e come valore di funzione, la dimensione della struttura
 */
uint32_t rtc_read(uint8_t *data, uint32_t size, char *flag)
{
	data = (char *) &rtc_data;
	return sizeof(rtc_data);
}


uint8_t rtc_get_seconds()
{
	io_outb(RTCaddress,0);
	return (uint8_t) bcd2bin(io_inb(RTCdata));
}

uint8_t rtc_get_minutes()
{
	io_outb(RTCaddress,0x02);
	return (uint8_t) bcd2bin(io_inb(RTCdata));
}


uint8_t rtc_get_hours()
{
	io_outb(RTCaddress,0x04);
	return (uint8_t) bcd2bin(io_inb(RTCdata));
}


uint8_t rtc_get_day()
{
	io_outb(RTCaddress,0x07);
	return (uint8_t) bcd2bin(io_inb(RTCdata));
}


uint8_t rtc_get_month()
{
	io_outb(RTCaddress,0x08);
	return (uint8_t) bcd2bin(io_inb(RTCdata));
}

uint8_t rtc_get_year()
{
	io_outb(RTCaddress,0x09);
	return (uint8_t) bcd2bin(io_inb(RTCdata));
}
